package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import gripper.ftp.DataSocket;
import gripper.ftp.Delay;
import gripper.ftp.FtpSession;
import gripper.ftp.PathConvert;

public class MLSDHandle implements Handle {
	FtpSession ftpSession;
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss.SSS", Locale.ENGLISH);

	public MLSDHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}

	public void process(String line, BufferedReader br, OutputStream os) throws IOException {
		os.write("150 Opening BINARY mode data connection for MLSD.\r\n".getBytes());
		os.flush();

		DataSocket sock = ftpSession.getClientSock();
		String path = PathConvert.toServerPath(ftpSession.getRootDir(), ftpSession.currentDir);
		File file = new File(path.trim());
		File[] files = file.listFiles();
		OutputStream outputStream = sock.getOutputStream();
		if (!file.exists()) {
			os.write("226 Transfer complete.\r\n".getBytes());
			os.flush();
			Delay.delay();
			sock.close();
			return;
		}
		if (files == null) {
			System.out.println(ftpSession.currentDir);
			System.out.println(file.getAbsolutePath());
			System.out.println(path);
			os.write("226 Transfer complete.\r\n".getBytes());
			os.flush();
			Delay.delay();
			sock.close();
			return;
		}
		for (File f : files) {
			String template = "Type=#{dir};#{size}Modify=#{time};Perm=#{perm}; #{fileName}\r\n";
			long time = f.lastModified();
			Date date = new Date(time);
			template = template.replace("#{time}", sdf.format(date));
			template = template.replace("#{fileName}", f.getName());
			if (f.isDirectory()) {
				template = template.replace("#{dir}", "dir");
				template = template.replace("#{perm}", "elmc");
				template = template.replace("#{size}", "");
			} else {
				template = template.replace("#{dir}", "file");
				template = template.replace("#{perm}", "rw");
				template = template.replace("#{size}", "Size=#{fileSize};");
				template = template.replace("#{fileSize}", Long.toString(f.length()));
			}
			System.out.println(template);
			outputStream.write(template.getBytes());
			outputStream.write("\r\n".getBytes());
			outputStream.flush();

		}
		os.write("226 Transfer complete.\r\n".getBytes());
		System.out.println("226 Transfer complete.\r\n");
		
		sock.close();
		os.flush();
		System.out.println("flush\r\n");
		//Delay.delay();
		//System.out.println("sock close\r\n");
	}
}
